package com.ktwlrj.securitycenter.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktwlrj.core.base.DetailEntity;
import com.ktwlrj.core.constant.ResultCode;
import com.ktwlrj.core.exception.ActionException;
import com.ktwlrj.core.util.ContextHolderUtils;
import com.ktwlrj.core.util.convert.ConvertUtil;
import com.ktwlrj.securitycenter.controller.args.AddSafeApproveArgs;
import com.ktwlrj.securitycenter.controller.args.SafeApproveArgs;
import com.ktwlrj.securitycenter.controller.args.SafeCredentialArgs;
import com.ktwlrj.securitycenter.controller.args.SafeCredentialInfoArgs;
import com.ktwlrj.securitycenter.controller.args.SafePassApplyArgs;
import com.ktwlrj.securitycenter.controller.args.SafePassApprovePageArgs;
import com.ktwlrj.securitycenter.controller.args.SafePassFormArgs;
import com.ktwlrj.securitycenter.controller.args.SafePassPageArgs;
import com.ktwlrj.securitycenter.dto.SafeApproveDto;
import com.ktwlrj.securitycenter.dto.SafeCredentialDto;
import com.ktwlrj.securitycenter.dto.SafePassApprovePageDto;
import com.ktwlrj.securitycenter.dto.SafePassDto;
import com.ktwlrj.securitycenter.dto.SafePassFormDto;
import com.ktwlrj.securitycenter.dto.SafePassPageDto;
import com.ktwlrj.securitycenter.dto.SafePassTargetDto;
import com.ktwlrj.securitycenter.em.LockStatusEnum;
import com.ktwlrj.securitycenter.entity.SafePassEntity;
import com.ktwlrj.securitycenter.entity.SafePassTargetEntity;
import com.ktwlrj.securitycenter.mapper.SafePassMapper;
import com.ktwlrj.securitycenter.mapper.SafePassTargetMapper;
import com.ktwlrj.securitycenter.service.SafeApproveService;
import com.ktwlrj.securitycenter.service.SafeCredentialService;
import com.ktwlrj.securitycenter.service.SafePassService;
import com.ktwlrj.securitycenter.service.SafePassTargetService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * (SafePass)业务层实现
 *
 * @author code generation
 * @date 2020-02-24 18:08:13
 * @since JDK1.8
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SafePassServiceImpl extends ServiceImpl<SafePassMapper, SafePassEntity> implements SafePassService {
	private final SafePassMapper mapper;
	private final SafePassTargetService passTargetService;
	private final SafePassTargetMapper passTargetMapper;
	private final SafeCredentialService credentialService;
	private final SafeApproveService approveService;
	private final ContextHolderUtils contextHolderUtils;

	@Override
	public void save(SafePassFormArgs args) throws RuntimeException {
		if (StringUtils.isBlank(args.getSafePass().getRuleCode())) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "规则编号不能为空");
		}
		if (args.getSafePassTargetList().size() <= 0) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "限制对象不能为空");
		}
		DetailEntity detailEntity = contextHolderUtils.getDetailEntity();
		SafePassEntity entity = ConvertUtil.map(args.getSafePass(), SafePassEntity.class);
		entity.setPassId(null);
		entity.setApproveStatus(0);
		entity.setVersion(null);
		entity.setTargetCount(args.getSafePassTargetList().size());
		entity.setOrgId(detailEntity.getCurrentOrgId());
		entity.setOrgName(detailEntity.getCurrentOrgName());
		entity.setLockStatus(LockStatusEnum.NORMAL.getValue());// 锁定状态
		entity.setHistoryType(10);// 历史类型
		super.save(entity);
		// 对象信息
		List<SafePassTargetEntity> passTargeList = ConvertUtil.listAtoListB(args.getSafePassTargetList(),
				SafePassTargetEntity.class);
		for (SafePassTargetEntity item : passTargeList) {
			item.setPassTargetId(null);
			item.setPassId(entity.getPassId());
			if (item.getScope() == 2) {
				item.setDataCode(item.getSaleCertificate());
			}
			if (item.getScope() == 3) {
				item.setDataCode(item.getBuildingNumber());
			}
			if (item.getScope() == 4) {
				item.setDataCode(item.getRoomNumber());
			}
		}
		passTargetService.saveBatch(passTargeList);
		// 添加要件信息
		for (SafeCredentialArgs item : args.getCredentialList()) {
			item.setBusiId(entity.getPassId());
			item.setCredentialId(null);
			List<SafeCredentialInfoArgs> credentialInfoList = item.getCredentialInfoList();
			for (SafeCredentialInfoArgs itemInfo : credentialInfoList) {
				itemInfo.setCredentialInfoId(null);
			}
		}
		credentialService.batchSave(args.getCredentialList());
	}

	@Override
	public void updateById(SafePassFormArgs args) throws RuntimeException {
		if (StringUtils.isBlank(args.getSafePass().getPassId())) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "业务放行id不能为空");
		}
		if (StringUtils.isBlank(args.getSafePass().getRuleCode())) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "规则编号不能为空");
		}
		if (args.getSafePassTargetList().size() <= 0) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "限制对象不能为空");
		}
		SafePassEntity entity = super.getById(args.getSafePass().getPassId());
		if (entity == null) {
			throw new ActionException(ResultCode.DATABASE_NODATA);
		}
		if (entity.getLockStatus() != null && entity.getLockStatus() != 10) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "当前记录处于锁定状态");
		}
		DetailEntity detailEntity = contextHolderUtils.getDetailEntity();
		entity = ConvertUtil.map(args.getSafePass(), SafePassEntity.class);
		entity.setApproveStatus(0);
		entity.setTargetCount(args.getSafePassTargetList().size());
		entity.setOrgId(detailEntity.getCurrentOrgId());
		entity.setOrgName(detailEntity.getCurrentOrgName());
		super.updateById(entity);
		// 对象信息
		QueryWrapper<SafePassTargetEntity> targetQueryWrapper = new QueryWrapper<>();
		targetQueryWrapper.lambda().eq(SafePassTargetEntity::getPassId, args.getSafePass().getPassId());
		passTargetMapper.delete(targetQueryWrapper);
		List<SafePassTargetEntity> passTargeList = ConvertUtil.listAtoListB(args.getSafePassTargetList(),
				SafePassTargetEntity.class);
		for (SafePassTargetEntity item : passTargeList) {
			item.setPassTargetId(null);
			item.setPassId(entity.getPassId());
			if (item.getScope() == 2) {
				item.setDataCode(item.getSaleCertificate());
			}
			if (item.getScope() == 3) {
				item.setDataCode(item.getBuildingNumber());
			}
			if (item.getScope() == 4) {
				item.setDataCode(item.getRoomNumber());
			}
		}
		passTargetService.saveBatch(passTargeList);
		// 添加要件信息
		for (SafeCredentialArgs item : args.getCredentialList()) {
			item.setBusiId(entity.getPassId());
			item.setCredentialId(null);
		}
		credentialService.batchSave(args.getCredentialList());
	}

	@Override
	public IPage<SafePassPageDto> page(SafePassPageArgs args) throws RuntimeException {
		args.setOrgId(contextHolderUtils.getCurrentOrgId());
		return mapper.page(args.getQueryPage(), args);
	}

	@Override
	public IPage<SafePassPageDto> historyPage(SafePassPageArgs args) throws RuntimeException {
		args.setOrgId(contextHolderUtils.getCurrentOrgId());
		return mapper.historyPage(args.getQueryPage(), args);
	}

	@Override
	public SafePassFormDto getById(String id) throws RuntimeException {
		SafePassFormDto safePassFormDto = new SafePassFormDto();
		SafePassEntity byId = super.getById(id);
		if (byId == null) {
			throw new ActionException(ResultCode.DATABASE_NODATA);
		}
		SafePassDto safePass = ConvertUtil.map(byId, SafePassDto.class);
		safePassFormDto.setSafePass(safePass);
		// 业务放行对象
		QueryWrapper<SafePassTargetEntity> targetQueryWrapper = new QueryWrapper<>();
		targetQueryWrapper.lambda().eq(SafePassTargetEntity::getPassId, id);
		List<SafePassTargetEntity> passTargetEntityList = passTargetMapper.selectList(targetQueryWrapper);
		List<SafePassTargetDto> safePassTargetList = ConvertUtil.listAtoListB(passTargetEntityList,
				SafePassTargetDto.class);
		safePassFormDto.setSafePassTargetList(safePassTargetList);
		// 要件信息
		List<SafeCredentialDto> safeCredentialList = credentialService.selectListByModel(id);
		safePassFormDto.setSafeCredentialList(safeCredentialList);
		// 审批意见
		List<SafeApproveDto> safeApproveList = approveService.selectByBusinessId(id);
		safePassFormDto.setSafeApproveList(safeApproveList);
		return safePassFormDto;
	}

	@Override
	public void submit(SafePassApplyArgs args) throws RuntimeException {
		SafePassEntity entity = super.getById(args.getPassId());
		if (entity == null) {
			throw new ActionException(ResultCode.DATABASE_NODATA);
		}
		// 新增
		if (entity.getPassType() == 1) {
			entity.setApproveStatus(10);
		}
		// 变更
		if (entity.getPassType() == 2) {
			QueryWrapper<SafePassEntity> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(SafePassEntity::getPassCode, entity.getPassCode());
			queryWrapper.lambda().eq(SafePassEntity::getApproveStatus, 20);
			SafePassEntity historySafePassEntity = mapper.selectOne(queryWrapper);
			entity.setApproveStatus(10);
			historySafePassEntity.setLockStatus(LockStatusEnum.LOGGING_OUT.getValue());
			mapper.updateById(historySafePassEntity);
		}
		mapper.updateById(entity);
		// 审批意见
		AddSafeApproveArgs addSafeApproveArgs = new AddSafeApproveArgs();
		addSafeApproveArgs.setBusinessId(entity.getPassId());
		addSafeApproveArgs.setApproveType(entity.getPassType());
		addSafeApproveArgs.setHandlePersonId(args.getHandlePersonId());
		addSafeApproveArgs.setHandlePersonName(args.getHandlePersonName());
		approveService.save(addSafeApproveArgs);
	}

	@Override
	public void changeInsert(SafePassFormArgs args) throws RuntimeException {
		// 查询数据是否存在
		SafePassEntity entity = super.getById(args.getSafePass().getPassId());
		if (entity == null) {
			throw new ActionException(ResultCode.DATA_INPUT_EMPTY.getValue(), "未查询到当前数据");
		}
		if (entity.getApproveStatus() != 20) {
			throw new ActionException(ResultCode.AUTH_ACCESS_DENIED.getValue(), "审批状态未通过，不能变更");
		}
		if (entity.getLockStatus() != null && entity.getLockStatus() != LockStatusEnum.NORMAL.getValue()) {
			throw new ActionException(ResultCode.AUTH_ACCESS_DENIED.getValue(), "当前数据处理锁定状态");
		}
		entity.setLockStatus(LockStatusEnum.LOGGING_OUT.getValue());
		boolean result = super.updateById(entity);
		if (!result) {
			throw new ActionException(ResultCode.DATABASE_UPDATE_ERROR);
		}
		// 保存
		args.getSafePass().setPassCode(args.getSafePass().getPassCode());
		this.save(args);
	}

	@Override
	public void deleteById(String id) throws RuntimeException {
		SafePassEntity entity = super.getById(id);
		if (entity == null) {
			throw new ActionException(ResultCode.DATABASE_NODATA);
		}
		if (entity.getApproveStatus() != 0 && entity.getApproveStatus() != 30) {
			throw new ActionException(ResultCode.VERIFICATION_FAILED.getValue(), "当前记录不能被删除");
		}
		// 原数据恢复锁定状态
		QueryWrapper<SafePassEntity> passQueryWrapper = new QueryWrapper<>();
		passQueryWrapper.lambda().ne(SafePassEntity::getPassId, id);
		passQueryWrapper.lambda().eq(SafePassEntity::getPassCode, entity.getPassCode());
		passQueryWrapper.lambda().eq(SafePassEntity::getApproveStatus, 20);
		SafePassEntity safePassEntity = mapper.selectOne(passQueryWrapper);
		if (safePassEntity != null) {
			safePassEntity.setLockStatus(10);
			mapper.updateById(safePassEntity);
		}

		mapper.deleteById(id);
		// 业务放行对象
		QueryWrapper<SafePassTargetEntity> targetQueryWrapper = new QueryWrapper<>();
		targetQueryWrapper.lambda().eq(SafePassTargetEntity::getPassId, id);
		passTargetMapper.delete(targetQueryWrapper);
		// 要件信息
		credentialService.deleteByBusiId(id);
		// 审批意见
		approveService.deleteByBusinessId(id);
	}

	@Override
	public void deleteApply(SafePassApplyArgs args) throws RuntimeException {
		SafePassEntity entity = super.getById(args.getPassId());
		if (entity == null) {
			throw new ActionException(ResultCode.DATABASE_NODATA);
		}
		entity.setLockStatus(LockStatusEnum.CANCELLING.getValue());
		mapper.updateById(entity);
		// 要件信息
		appendCredential(args);
		// 审批意见
		AddSafeApproveArgs addSafeApproveArgs = new AddSafeApproveArgs();
		addSafeApproveArgs.setBusinessId(entity.getPassId());
		addSafeApproveArgs.setApproveType(3);
		addSafeApproveArgs.setHandlePersonId(args.getHandlePersonId());
		addSafeApproveArgs.setHandlePersonName(args.getHandlePersonName());
		approveService.save(addSafeApproveArgs);

	}

	/**
	 * 追加要件信息
	 *
	 * @param args
	 *            请求参数
	 */
	private void appendCredential(SafePassApplyArgs args) {
		if (args.getCredentialInfoList() != null && args.getCredentialInfoList().size() > 0) {
			List<SafeCredentialDto> credentialDtoList = credentialService.selectListByModel(args.getPassId());
			List<SafeCredentialArgs> credentialArgsList = new ArrayList<>();
			if (credentialDtoList != null && credentialDtoList.size() > 0) {
				credentialArgsList = ConvertUtil.listAtoListB(credentialDtoList, SafeCredentialArgs.class);
			} else {
				SafeCredentialArgs safeCredentialArgs = new SafeCredentialArgs();
				safeCredentialArgs.setBusiId(args.getPassId());
				safeCredentialArgs.setCredentialType("复印件");
				safeCredentialArgs.setCredentialName("凭证");
				safeCredentialArgs.setCredentialCount(1);
				safeCredentialArgs.setCredentialPage(1);
				safeCredentialArgs.setFileType(0);
				safeCredentialArgs.setSortId(0);
				safeCredentialArgs.setInterOperateType(1);
				safeCredentialArgs.setNetOperateType(1);
				credentialArgsList.add(safeCredentialArgs);
			}
			for (SafeCredentialArgs item : credentialArgsList) {
				if (item.getCredentialName().equals("凭证")) {
					item.getCredentialInfoList().addAll(args.getCredentialInfoList());
					break;
				}
			}
			credentialService.batchSave(credentialArgsList);
		}
	}

	@Override
	public IPage<SafePassApprovePageDto> approvePage(SafePassApprovePageArgs args) throws RuntimeException {
		DetailEntity detailEntity = contextHolderUtils.getDetailEntity();
		args.setOrgId(detailEntity.getCurrentOrgId());
		args.setMemberId(detailEntity.getMemberId());
		return mapper.approvePage(args.getQueryPage(), args);
	}

	@Override
	public void approveHandle(SafeApproveArgs args) throws RuntimeException {
		// 查询数据是否存在
		SafeApproveDto approveDto = approveService.getById(args.getApproveId());
		// 已经通过的数据置为历史
		SafePassEntity safePassEntity = super.getById(args.getBusinessId());

		QueryWrapper<SafePassEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(SafePassEntity::getPassCode, safePassEntity.getPassCode());
		queryWrapper.lambda().eq(SafePassEntity::getApproveStatus, 20);
		SafePassEntity historySafePassEntity = mapper.selectOne(queryWrapper);
		// 审批通过
		if (args.getHandleResult() == 1) {
			// 新增
			if (approveDto.getApproveType() == 1) {
				safePassEntity.setApproveStatus(20);
				safePassEntity.setVersion(1);
				safePassEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
				safePassEntity.setApproveTime(new Date());
			}
			// 变更
			if (approveDto.getApproveType() == 2) {
				if (historySafePassEntity == null) {
					throw new ActionException(ResultCode.VERIFICATION_FAILED, "未查询到变更前数据");
				}
				safePassEntity.setApproveStatus(20);
				safePassEntity.setVersion(historySafePassEntity.getVersion() + 1);
				safePassEntity.setApproveTime(new Date());
				safePassEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
				historySafePassEntity.setApproveStatus(40);
				historySafePassEntity.setHistoryType(20);
				historySafePassEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
				mapper.updateById(historySafePassEntity);
			}
			// 删除
			if (approveDto.getApproveType() == 3) {
				safePassEntity.setApproveStatus(40);
				safePassEntity.setApproveTime(new Date());
				safePassEntity.setHistoryType(30);
				safePassEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
			}
		}
		// 驳回
		if (args.getHandleResult() == 2) {
			// 新增
			if (approveDto.getApproveType() == 1) {
				safePassEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
				safePassEntity.setApproveStatus(30);
			}
			// 变更
			if (approveDto.getApproveType() == 2) {
				if (historySafePassEntity == null) {
					throw new ActionException(ResultCode.VERIFICATION_FAILED, "未查询到变更前数据");
				}
				// 新数据审批状态未通过
				safePassEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
				safePassEntity.setApproveStatus(30);
				// 老数据审批状态已通过
				historySafePassEntity.setApproveStatus(20);
				historySafePassEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
				mapper.updateById(historySafePassEntity);
			}
			// 删除
			if (approveDto.getApproveType() == 3) {
				safePassEntity.setLockStatus(LockStatusEnum.NORMAL.getValue());
			}
		}
		mapper.updateById(safePassEntity);
		approveService.approveSave(args);
	}
}